﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MultLanguage.NLS
{
    /// <summary>
    /// 多语言配置文件
    /// </summary>
    public class SLConfigFile
    {
        private string _strError = "";
        public string ErrorMessage
        {
            get
            {
                return _strError;
            }
        }

        private ExeConfigurationFileMap file;

        private string ConfigFilePath = "MultLanguage//NationalLanguageCodes.xml";

        private Configuration _config;

        private Dictionary<string, string> _dicLocalLans = new Dictionary<string, string>();
        public Dictionary<string, string> LocalLanguages
        {
            get { return _dicLocalLans; }
        }

        public List<KeyValuePair<string, string>> AllLanguages = new List<KeyValuePair<string, string>>();    

        /// <summary>
        /// 新建或打开文件
        /// </summary>
        /// <param name="strFilePath">文件名</param>
        public SLConfigFile(string strFilePath)
        {
            ConfigFilePath = strFilePath;
        }

        public bool Init()
        {
            try
            {
                file = new ExeConfigurationFileMap();
                file.ExeConfigFilename = ConfigFilePath;
                bool bExists = File.Exists(ConfigFilePath);
                _config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
                if (!bExists)
                {
                    AddSection();                 
                    List<KeyValuePair<string, string>> list = ReadCodes();
                    InitData(list);
                    AddLocalLanuageCode("zh-CN");
                    AddLocalLanuageCode("ko");
                    AddLocalLanuageCode("ru");
                    AddLocalLanuageCode("en");
                    AddLocalLanuageCode("fr");
                    AddLocalLanuageCode("es");
                    Save();
                }
                else
                {
                    LoadSupportLanuageItems();
                    LoadLocalLanuageItems();
                }
                return true;
            }
            catch (Exception ex)
            {
                _strError = ex.ToString();
                return false;
               // Log.WriteAsync();
            }
        }

        private List<KeyValuePair<string, string>> ReadCodes()
        {
            List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
            string filePath = Path.Combine(Application.StartupPath, "MultLanguage//codes.txt");
            list.Clear();
            using (StreamReader stream = new StreamReader(filePath, Encoding.Default))
            {
                string str;
                int i = 0;
                while ((str = stream.ReadLine()) != null)
                {
                    string[] s = str.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (s.Length != 2)
                    {
                        MessageBox.Show(i.ToString());
                    }
                    else
                    {
                        list.Add(new KeyValuePair<string, string>(s[0], s[1]));
                    }
                    i++;
                }
            }
            return list;
        }

        public void InitData(List<KeyValuePair<string, string>> list)
        {
            NLSSection section = _config.GetSection("NLSSection") as NLSSection;
            NLSCollection collection = section.Items;
            for (int i = 0; i < list.Count; i++)
            {
                string key = list[i].Key;
                string value = list[i].Value;
                NLSElement item = collection[key];
                if (item == null)
                {
                    collection.Add(new NLSElement(key, value));
                }
                else
                {
                    collection[key].Nation = value;
                }
            }
            Save();
            LoadLocalLanuageItems();
            LoadSupportLanuageItems();
        }

        private void AddSection()
        {
            _config.Sections.Add("NLSSection", new NLSSection());
            _config.Sections.Add("LocalLanuageSection", new LocalLanuageSection());
        }

        /// <summary>
        /// 写入一个本地语言子项节点
        /// </summary>
        /// <param name="first"></param>
        /// <param name="second"></param>
        public bool AddLocalLanuageCode(string code)
        {         
            NLSSection section_NLS = _config.GetSection("NLSSection") as NLSSection;
            NLSCollection collection_NLS = section_NLS.Items;
            NLSElement elem = collection_NLS[code];
            if (elem == null)
            {
                MessageBox.Show("不存在的区域语言代码: " + code);
                return false;
            }
            string nation = elem.Nation;
            LocalLanuageSection section = _config.GetSection("LocalLanuageSection") as LocalLanuageSection;
            LocalLanuageElement item = section.Items[code];
            if (item == null)
            {
                section.Items.Add(new LocalLanuageElement(nation, code));
            }
            else
            {
                section.Items[code].Nation = nation;
            }
            return true;
        }

        /// <summary>
        /// 移除一个双语子项节点
        /// </summary>
        /// <param name="key">关键词</param>
        public void RemoveLocalLanuageCode(string key)
        {
            LocalLanuageSection section = _config.GetSection("LocalLanuageSection") as LocalLanuageSection;
            LocalLanuageElement item = section.Items[key];
            if (item != null)
            {
                section.Items.Remove(key);
            }
        }

        /// <summary>
        /// 获取本地语言代码列表
        /// </summary>
        /// <returns></returns>
        public void LoadLocalLanuageItems()
        {
            try
            {
                _dicLocalLans.Clear();
                LocalLanuageSection section = _config.GetSection("LocalLanuageSection") as LocalLanuageSection;
                LocalLanuageCollection collection = section.Items;
                int nCount = collection.Count;
                for (int i = 0; i < nCount; ++i)
                {
                    _dicLocalLans.Add(collection[i].Code, collection[i].Nation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 获取区域语言代码列表
        /// </summary>
        /// <returns></returns>
        public void LoadSupportLanuageItems()
        {
            try 
            {
                AllLanguages.Clear();
                NLSSection section = _config.GetSection("NLSSection") as NLSSection;
                NLSCollection collection = section.Items;
                int nCount = collection.Count;     
                for (int i = 0; i < nCount; ++i)
                {
                    string strKey = collection[i].Code;
                    string strValue = collection[i].Nation;
                    AllLanguages.Add(new KeyValuePair<string, string>(strKey, strValue));
                }
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.ToString());
            }          
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public void Save()
        {
            _config.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("BilingualSection");            
        }

        public string GetNation(string code)
        {
            KeyValuePair<string, string> pair = AllLanguages.Find(r=>r.Key.Equals(code));
            if (!string.IsNullOrEmpty(pair.Key) && pair.Key.Equals(code))
            {
                return pair.Value;
            }
            else
            {
                NLSSection section = _config.GetSection("NLSSection") as NLSSection;
                NLSElement elem = section.Items[code];
                if (elem != null)
                {
                    return elem.Nation;
                }
                else
                {
                    return "";
                }
            }
        }

    }
}
